/*
*    Qizx/open 3.0 beta
*
* This code is the open-source version of Qizx.
* Copyright (C) 2004-2009 Axyana Software -- All rights reserved.
*
* The contents of this file are subject to the Mozilla Public License 
*  Version 1.1 (the "License"); you may not use this file except in 
*  compliance with the License. You may obtain a copy of the License at
*  http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
*  WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
*  for the specific language governing rights and limitations under the
*  License.
*
* The Initial Developer of the Original Code is Xavier Franc - Axyana Software.
*
*/
using System;
using EvaluationException = System.Qizx.Api.EvaluationException;
using XQItem = System.Qizx.XQuery.XQItem;
using XQValue = System.Qizx.XQuery.XQValue;
namespace System.Qizx.XQuery.Dt
{
	
	/// <summary> A sequence that stores String items in an array.</summary>
	public class StringArraySequence:GenericValue
	{
		protected internal System.String[] items;
		
		protected internal int size;
		
		protected internal int index = - 1;
		
		public StringArraySequence(System.String[] items, int size)
		{
			this.items = items;
			this.size = size;
		}
		
		public override bool Next()
		{
			if (++index >= size)
				return false;
			item = new SingleString(items[index]); // Hmmm
			return true;
		}
		
		public override XQItem QuickIndex(long index)
		{
			return index <= 0 || index > size?null:new SingleString(items[(int) index - 1]);
		}
		
		public override XQValue BornAgain()
		{
			return new StringArraySequence(items, size);
		}
		
		/// <summary> Converts a Value representing a sequence of strings into an array.</summary>
		public static System.String[] expand(XQValue value_Renamed)
		{
			System.String[] items = new System.String[8];
			int ptr = 0;
			for (; value_Renamed.Next(); )
			{
				if (ptr >= items.Length)
				{
					System.String[] old = items;
					items = new System.String[old.Length * 2];
					Array.Copy(old, 0, items, 0, old.Length);
				}
				items[ptr++] = value_Renamed.ValueAsString;
			}
			// return a full array: TODO OPTIM
			System.String[] ritems = new System.String[ptr];
			Array.Copy(items, 0, ritems, 0, ptr);
			return ritems;
		}
	}
}